package com.situ.mall.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mall.api.product.ProductClient;
import com.situ.mall.api.user.UserClient;
import com.situ.mall.common.util.Result;
import com.situ.mall.order.mapper.OrderItemMapper;
import com.situ.mall.order.pojo.query.OrderInfoQuery;
import com.situ.mall.order.pojo.query.OrderQuery;
import com.situ.mall.order.pojo.vo.OrderCountVO;
import com.situ.mall.order.pojo.vo.OrderInfoVO;
import com.situ.mall.order.service.IOrderInfoService;
import com.situ.mall.pojo.entity.order.OrderInfo;
import com.situ.mall.pojo.entity.order.OrderItem;
import com.situ.mall.pojo.entity.product.Product;
import com.situ.mall.pojo.entity.user.User;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.*;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Sun Huijuan
 * @since 2024-10-14
 */
@RestController
@RequestMapping("/order/orderInfo")
public class OrderInfoController {
	@Autowired
	private IOrderInfoService orderInfoService;
	@Autowired
	private OrderItemMapper orderItemMapper;
	@Autowired
	private ProductClient productClient;
	@Autowired
	private UserClient userClient;
	
	@PostMapping("/add")
	public Result add(@RequestBody OrderInfo orderInfo){
		//orderInfo里面有userId和addressId
		orderInfoService.add(orderInfo);
		return Result.ok("下单成功！");
	}
	
	//前台
	@GetMapping("/selectList")
	public Result<Map<String,Object>> selectList(OrderInfoQuery orderInfoQuery){
		IPage<Map<String,Object>> listPage = orderInfoService.selectList(orderInfoQuery);
		Map<String,Object> map = new HashMap<>();
		map.put("records",listPage.getRecords());
		map.put("total",listPage.getTotal());
		return Result.ok(map);
	}
	
	@GetMapping("/list")
	public Result<List<OrderInfoVO>> list(OrderInfoQuery orderInfoQuery){
		List<OrderInfoVO> list= orderInfoService.list(orderInfoQuery);
		return Result.ok(list);
	}
	
	//【后台管理——分页&搜索查询】
	@GetMapping("/selectByPage")
	public Result selectByPage(OrderQuery orderQuery){
		IPage<OrderInfo> page = new Page<>(orderQuery.getPage(), orderQuery.getLimit());
		QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.like(!ObjectUtils.isEmpty(orderQuery.getUserName()), "user_name", orderQuery.getUserName());
		queryWrapper.between(!ObjectUtils.isEmpty(orderQuery.getBeginCreateTime())&&!ObjectUtils.isEmpty(orderQuery.getEndCreateTime()),
				"create_time",orderQuery.getBeginCreateTime(),orderQuery.getEndCreateTime());
		queryWrapper.orderByDesc("create_time");
		orderInfoService.page(page, queryWrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("total", page.getTotal());
		map.put("list", page.getRecords());
		return Result.ok(map);
	}
	
	//【后台管理——查看详情】
	@GetMapping("/selectById/{id}")
	public Result<OrderInfoVO> selectById(@PathVariable Long id){
		OrderInfoVO orderInfoVO = orderInfoService.selectById(id);
		return Result.ok(orderInfoVO);
	}
	
	//【前台用户操作：付款/收货】
	@PutMapping("/updateStatus")
	public Result updateStatus(@RequestBody OrderInfo orderInfo){
		if (orderInfo.getOrderStatus()==2){
			OrderInfo orderInfo1=orderInfoService.selectById(orderInfo.getId());
			User user =userClient.selectById(orderInfo.getUserId()).getData();
			if ((user.getBalance()).compareTo(orderInfo1.getTotalAmount())<0){
				//余额不足
				return Result.error("余额不足，付款失败！");
			}else {
				user.setBalance((user.getBalance()).subtract(orderInfo1.getTotalAmount()));
				userClient.updateSelf(user);
				orderInfoService.updateById(orderInfo);
				return Result.ok("付款成功！");
			}
		}else{
			orderInfoService.updateById(orderInfo);
			return Result.ok("收货成功！");
		}
	}
	
	//【后台管理】——批量删除
	@DeleteMapping("/deleteAll/{ids}")
	public Result<Object> deleteAll(@PathVariable Integer[] ids) {
		orderInfoService.removeByIds(Arrays.asList(ids));
		return Result.ok("删除成功！");
	}
	
	//【后台管理】——单个删除
	@DeleteMapping("/deleteById/{id}")
	public Result deleteById(@PathVariable Integer id) {
		orderInfoService.removeById(id);
		return Result.ok("删除成功！");
	}
	
	//【后台管理——发货】
	@PutMapping("/deliver/{id}")
	public Result deliver(@PathVariable Long id){
		orderInfoService.updateStatus(id,3);
		//减库存
		OrderInfo orderInfo=orderInfoService.getById(id);
		QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("order_no",orderInfo.getOrderNo());
		List<OrderItem> orderItemList=orderItemMapper.selectList(queryWrapper);
		for (OrderItem orderItem:orderItemList){
			Product product= productClient.selectById(orderItem.getProductId()).getData();
			int newNum=product.getStock()-orderItem.getQuantity();
			product.setStock(newNum);
			if (!ObjectUtils.isEmpty(product)){
				productClient.update(product);
			}
		}
		return Result.ok("发货成功！");
	}
	
	//【后台管理——统计图表：本月每日订单数量】
	@GetMapping("/selectOrderGrowth")
	public Result selectOrderGrowth() {
		List<OrderCountVO> list = orderInfoService.selectOrderCount();
		return Result.ok(list);
	}
	
	//【后台管理——统计图表：统计销售额】
	@GetMapping("/selectSaleCount")
	public Result<BigDecimal> selectSaleCount() {
		return Result.ok(orderInfoService.selectSaleCount());
	}
	
	//【后台管理——统计图表：统计订单总数】
	@GetMapping("/selectOrderCount")
	public Result selectOrderCount(){
		return Result.ok(orderInfoService.count());
	}
	
	//【后台管理】——导出Excel
	@GetMapping("/exportExcel")
	public void exportExcel(HttpServletResponse response){
		orderInfoService.exportExcel(response);
	}
}

